import { PrismaClient } from '@prisma/client';
import { NextResponse } from 'next/server';
import { STATUS_CODES, STATUS_MESSAGES } from '@/lib/constants/statusCode';

const prisma = new PrismaClient();

export async function POST(request) {
  try {
    const { userId, name, cards } = await request.json();
    
    console.log(cards)

    // 验证必要参数
    if (!userId) {
      return NextResponse.json(
        { error: '用户id不能为空' },
        { status: STATUS_CODES.BAD_REQUEST }
      );
    }
    if (!name) {
      return NextResponse.json(
        { error: '卡组名称不能为空' },
        { status: STATUS_CODES.BAD_REQUEST }
      );
    }
    if (!Array.isArray(cards) || cards.length === 0) {
      return NextResponse.json(
        { error: '卡牌列表不能为空' },
        { status: STATUS_CODES.BAD_REQUEST }
      );
    }

    // 查找用户
    const user = await prisma.user.findUnique({
      where: { id: userId.toLowerCase() }
    });

    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: STATUS_CODES.NOT_FOUND }
      );
    }

    // 创建卡组和关联卡牌
    const deck = await prisma.deck.create({
      data: {
        name,
        userId: user.id,
        cards: {
          create: cards.map(cardId => ({
            cardId
          }))
        }
      },
      include: {
        cards: true
      }
    });

    return NextResponse.json({
      id: deck.id,
      name: deck.name,
      userId: deck.userId,
      cards: deck.cards.map(card => card.cardId),
      createdAt: deck.createdAt
    });

  } catch (error) {
    console.error('创建卡组失败:', error);
    return NextResponse.json(
      { error: STATUS_MESSAGES[STATUS_CODES.INTERNAL_SERVER_ERROR] },
      { status: STATUS_CODES.INTERNAL_SERVER_ERROR }
    );
  }
}